package com.github.tyc1210.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tyc1210.annotation.DataSource;
import com.github.tyc1210.annotation.MultiTransaction;
import com.github.tyc1210.dao.UserMapper;
import com.github.tyc1210.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Lazy
    private UserService userService;

    @DataSource("master")
    @Override
    public List<User> findUserFromMaster() {
        Wrapper<User> wrapper = new QueryWrapper<>();
        List<User> users = userMapper.selectList(wrapper);
        return users;
    }

    @DataSource("slave1")
    @Override
    public List<User> findUserFromSlave() {
        Wrapper<User> wrapper = new QueryWrapper<>();
        List<User> users = userMapper.selectList(wrapper);
        return users;
    }

    @Override
    @DataSource("master")
    public void saveUserMaster() {
        User user = new User();
        user.setName("master111");
        user.setPsw("6666");
        userMapper.insert(user);
    }

    @Override
    @DataSource("slave1")
    public void saveUserSlave() {
        User user = new User();
        user.setName("slave1111");
        user.setPsw("7777");
        userMapper.insert(user);
    }

    /**
     * 测试多数据源事务管理
     * 若没使用 MultiTransaction 只是使用 Transactional 以下操作将会使得数据插入到同一张表中、
     * 因为 spring 开启事务时会只会与一个connection进行绑定
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    @MultiTransaction
    public void testTrance() {
        userService.saveUserMaster();
        userService.saveUserSlave();
        int a = 1 / 0;

    }


}
